<?php

/**
 * Created by PhpStorm.
 * User: wyr
 * Date: 14-10-8
 * Time: 下午10:14
 */
class Controller_Wwwmall3_Service extends FController
{
    /**
     *处理微信服务器消息
     */
    public function defaultAction()
    {
        global $_F;

        $_F['s_url'] = 'http://img1.yuanfenba.net';
        $_F['s_url_oss'] = 'http://image1.yuanfenba.net'; //FConfig::get('global.s_url_oss');

        $logger = new FLogger("weixin");

        require_once(APP_ROOT . 'lib/weixin/WeixinChat.class.php');
        $options = array(
            'token' => FConfig::get('wechat.token'),
            'appid' => FConfig::get('wechat.appid'),
            'appsecret' => FConfig::get('wechat.appsecret'),
        );
        $weixin = new WeixinChat($options);

        //$weixin->valid();  //微信验证时打开，验证完关闭

        $logger->append('==============开始：===============');

        $getRev = $weixin->getRev();

        $logger->append($getRev->getRevText());

        if ($weixin->getRevType()) {

            $openid = $weixin->getRevFrom();

            $logger->append('openid:' . $openid);

            $logger->append('getRevType:' . $weixin->getRevType());
            $eventData = $weixin->getRevEvent();

            $logger->append('eventData:' . var_export($eventData, true));

            $MsgType = $weixin->getRevType();

            if ($MsgType) {

                if ($MsgType == 'text' || $MsgType == 'image' || $MsgType == 'voice' || $MsgType == 'video' || $MsgType == 'video' || $MsgType == 'shortvideo' || $MsgType == 'link') {

                    FLogger::write($MsgType, 'MsgType');

                }

                //在公众号里回复 清除缓存 服务器返回清除cookie链接
                if ($MsgType == 'text') {

                    $revText = $weixin->getRevText();

                    if ($revText == '清除缓存') {

                        $weixin->text('请点击打开此链接清除缓存 http://' . $_F['http_host'] . '/Public/deleteCookie');
                        $weixin->reply();

                    }else{

                    }
                }
            }
            if ($eventData) {
                if ($eventData['event'] == 'click') {
                    switch ($eventData['key']) {
                        case 'V1001_FREE':
                            $type = 1;
                            break;
                        case 'V1001_TODAY_ACTIVITY':
                            $type = 2;
                            break;
                        case 'V1001_FOUND':
                            $type = 3;
                            break;
                        case 'DRAW_WEAL':
                            $options = array(
                                'token' => FConfig::get('wechat.wxpay.token'),
                                'appid' => FConfig::get('wechat.wxpay.appid'),
                                'appsecret' => FConfig::get('wechat.wxpay.appsecret'),
                            );
                            $weixin1 = new WeixinChat($options);
                            $tmp_data = "前方高能请注意！为了优化公众号,更好地为大家服务, 从2017年9月09日开始“一只小红薯外卖”公众号所有业务转移至“一只小红薯”公众号，请各位小伙伴添加新号领取新号福利哦！给您造成不便敬请谅解！";

                            $weixin1->sendCustomMessage($openid,$tmp_data,'text');

                            sleep(1);
                            $weixin1->sendCustomMessage($openid,'45wHduLrRYXAjCWdio873nTG5tyorz1ljmMtyWwxboY','image');

                            //$userInfo = $weixin1->getUserInfo($openid);
                            //$weixin1->text($tmp_data);

                            //$weixin1->reply();
                            return;
                            break;
                        default:
                            $type = 1;
                            break;
                    }
                } else {

                    //扫码
                    if ($eventData['event'] == 'scan') {
                        if ($openid) {
                            //更新最后操作时间
                            Service_User::updateLastTimeByUid($openid);
                        }
                    }

                    if ($eventData['event'] == 'view') {
                        if ($openid) {
                            //更新最后操作时间
                            Service_User::updateLastTimeByUid($openid);
                        }
                    }

                    //关注
                    if ($eventData['event'] == 'subscribe') {

                        $data = "嘿，居然被你找到了？\n长沙骨灰级吃货才懂的美食专属号。\n\n红薯新吃法，赶紧尝尝鲜~\n百种口味+百变造型。\n点击【外卖】足不出户即可享用美食~\n小红薯等待各位小主翻牌~";

                        //$weixin->sendCustomMessage($openid,$data1,'text');

                        //$weixin->sendCustomMessage($openid,'45wHduLrRYXAjCWdio873jnIas-ouWkCAQT0CRE7Yio','image');

                        $userInfo = $weixin->getUserInfo($openid);
                        FLogger::write($userInfo, 'subscribe');


                        $user_wechat_scan_data = Service_User::getUserInfo($openid);//根据openid获取用户信息
                        if (!$user_wechat_scan_data) {
                            try {
                                $result = array(
                                    'openid' => $openid,
                                    'nickname' => $userInfo['nickname'],
                                    'sex' => $userInfo['sex'],
                                    'city' => $userInfo['city'],
                                    'province' => $userInfo['province'],
                                    'headimgurl' => $userInfo['headimgurl'],
                                    'subscribe' => 1,
                                    'subscribe_time' => $userInfo['subscribe_time'],
                                    'last_operation_time' => time() + 60 * 60 * 24 * 2,
                                );
                                Service_User::saveUser($result);
                            } catch (Exception $e) {

                            }
                        } else {
                            //帐号已存在，激活关注状态
                            Service_User::activationSubscribe($openid);
                            if ($openid) {
                                //更新最后操作时间
                                Service_User::updateLastTimeByUid($openid);
                            }
                        }
                    }

                    //取消关注
                    if ($eventData['event'] == 'unsubscribe') {
                        //取消关注
                        Service_User::cancelSubscribe($openid);
                    }

                    if ($eventData['event'] == 'location') {

                        $Location = $weixin->getRevLocation();

                        FLogger::write($Location, 'subscribe');
                        if ($openid) {
                            //更新最后操作时间
                            Service_User::updateLastTimeByUid($openid);
                        }

                    }
                }
            }


            if (isset($data)) {
                $logger->append(var_export($data, true));
                $logger->append(FRequest::getClientIP());

                if (is_array($data)) {
                    $weixin->news($data);
                } else {
                    $weixin->text($data);
                }

                $weixin->reply();
            }
        } else {
            $logger->append('getRevType为空' . $weixin->getRevType());
        }
        $logger->append('==============结束：===============');
    }

    function showMessage($message, $msgType, $url = null)
    {
        // TODO: Implement showMessage() method.
    }
}